import { message, Button, Divider, Tabs, Popconfirm } from 'antd'
import React, {useState, useRef, useEffect} from 'react'
import {PageHeaderWrapper} from '@ant-design/pro-layout'
import ProTable, {ProColumns, ActionType} from '@ant-design/pro-table'
import {connect, history} from 'umi'
import {
  getScorePage,
  saveAndUpdateScore,
  deleteScore,
  updateScoreStatus,
  updateScoreStop,
  getSelectProgram
} from '../service'
import moment from 'moment';
import {ratingStatus} from "@/utils/constant";
import CreateForm from './components/CreateForm'
import Detail from "@/pages/ScoreOf360/List/components/Detail";

const {TabPane} = Tabs;

const TableList = () => {
  const actionRef = useRef();
  const actionRef2 = useRef();
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [current, setCurrent] = useState(null);
  const [tabKey, setTabKey] = useState('0');
  const [scoreTypes, setScoreTypes] = useState([]);


  useEffect(() => {
    getSelectProgram().then(res => {
      let obj = {};
      res.forEach(item => { obj[item.id] = {text: item.programName} });
      setScoreTypes(obj);
    })
  }, []);

  const columns = [
    {
      title: '编号',
      render: (text, record, index) => `${index + 1}`,
      hideInSearch: true,
    },
    {
      title: '被评分人',
      dataIndex: 'name',
    },
    {
      title: '公司',
      dataIndex: 'orgName',
    },
    {
      title: '部门',
      dataIndex: 'unitName',
    },
    {
      title: '岗位',
      dataIndex: 'jobName',
      hideInSearch: true,
    },
    {
      title: '评分原因',
      dataIndex: 'programId',
      valueEnum: scoreTypes
    },
    {
      title: '分数',
      dataIndex: 'score',
      hideInSearch: true,
    },
    {
      title: '完成率',
      dataIndex: 'appraisalTare',
      hideInSearch: true,
      render: text => `${text !== '-' ? text : 0}%`
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: tabKey === '0' ?
        {
          0: {text: ratingStatus[0].label, status: 'Default'},
          1: {text: ratingStatus[1].label, status: 'Processing'}
        } :
        {
          2: {text: ratingStatus[2].label, status: 'Success'},
          3: {text: ratingStatus[3].label, status: 'Error'}
        },
    },
    {
      title: '操作人',
      dataIndex: 'createName',
    },
    {
      title: '创建日期',
      dataIndex: 'createTime',
      hideInSearch: true,
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : ''
      }
    },
    {
      title: '操作',
      dataIndex: 'option',
      hideInSearch: true,
      render: (item, record) => (
        <>
          {record.status === 0 && <><a onClick={() => openRating(record)}>修改</a>
            <Divider type="vertical"/><a onClick={() => initiate(record.id)}>发起</a>
            <Divider type="vertical"/>
            <Popconfirm title="是否确认删除？" cancelText='取消' okText='确认' onConfirm={() => deleteScoreOf360(record.id)}>
              <a>删除</a>
            </Popconfirm></>}
          {record.status === 1 && <>
            <Popconfirm title="是否确认终止？" cancelText='取消' okText='确认' onConfirm={() => termination(record.id)}>
              <a>终止</a>
            </Popconfirm>
            <Divider type="vertical"/></>}
          {record.status !== 0 && <><a onClick={() => shoeDetail(record)}>查看详情</a></>}
        </>
      ),
    },
  ];

  const handleChangTabIndex = (key) => {
    setTabKey(key);
    if (key === '0') {
      actionRef.current && actionRef.current.reload();
    } else {
      actionRef2.current && actionRef2.current.reload();
    }
  };

  const openRating = (record) => {
    setVisible(true);
    if (record)
      setCurrent(record);
  };

  const initiate = (id) => {
    updateScoreStatus(id).then(res => {
      if (res.flag) {
        message.success('发起评分成功！')
      } else {
        message.error(res.error);
      }
      actionRef.current.reload();
    })
  };

  const termination = (id) => {
    updateScoreStop(id).then(res => {
      if (res.flag) {
        message.success('终止成功！')
      } else {
        message.error(res.error);
      }
      actionRef.current.reload();
    })
  };

  const deleteScoreOf360 = (id) => {
    deleteScore(id).then(res => {
      if (res.flag) {
        message.success('删除评分成功！');
      } else {
        message.error(res.error);
      }
      actionRef.current.reload();
    })
  };

  const onFormSubmit = values => {
    saveAndUpdateScore(values).then(res => {
      if (res.flag) {
        message.success('新建评分成功');
      } else {
        message.error(res.error);
      }
      onFormCancel();
      actionRef.current.reload();
    })
  };

  const shoeDetail = record => {
    setDetailVisible(true);
    setCurrent(record);
  };

  const onFormCancel = () => {
    setVisible(false);
    setCurrent(null);
  };

  const onDetailCancel = () => {
    setDetailVisible(false);
    setCurrent(null);
  };

  return (
    <PageHeaderWrapper>
      <Tabs animated={false} defaultActiveKey="0" onChange={handleChangTabIndex}>
        <TabPane tab="待办理" key="0">
          <ProTable
            actionRef={actionRef}
            loading={loading}
            rowKey="id"
            toolBarRender={(action, {selectedRows}) => [
              <Button type="primary" onClick={() => openRating(null)}>新建</Button>,
            ]}
            request={(params) => getScorePage(params,[0,1], 0)}
            columns={columns}
          />
        </TabPane>
        <TabPane tab="已办理" key="1">
          <ProTable
            actionRef={actionRef2}
            rowKey="id"
            request={(params) => getScorePage(params, [2,3], 1)}
            columns={columns}
          />
        </TabPane>
      </Tabs>
      <CreateForm
        visible={visible}
        current={current}
        onCancel={onFormCancel}
        onSubmit={onFormSubmit}
      />
      <Detail
        visible={detailVisible}
        current={current}
        onCancel={onDetailCancel}
      />
    </PageHeaderWrapper>
  )
};

export default connect(({}) => ({}))(TableList)

